﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Kooboo.HtmlFunc;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.CMS.SiteConverter.Parser.Razor
{
    public class HtmlBlockPartParser : ParserBase, IParser<IHtmlBlockPart>
    {
        public static string GetInnerHtml(IHtmlBlockPart block)
        {
            return NodeExtension.GetInnerContent(block.StartNode, block.EndNode);
        }

        public static void ReplateInner(IHtmlBlockPart block, HtmlNode inner)
        {
            NodeExtension.ReplaceInner(block.StartNode, block.EndNode, inner);

            if (ParserSetting.RemoveFuncMarkers)
            {
                if (block.StartNode == block.EndNode)
                {
                    // attribute mode is obsoleted
                }
                else
                {
                    block.EndNode.RemoveWithPrevWhitespace();
                    block.StartNode.ParentNode.RemoveChild(block.StartNode);
                }
            }
        }

        public static void FillResult(ParserContext context, IHtmlBlockPart obj, string renderCode)
        {
            var htmlBlock = new Kooboo.CMS.Sites.Models.HtmlBlock()
            {
                Body = GetInnerHtml(obj),
                Name = obj.BlockName
            };

            if (obj.OwnerPosition != null)
            {
                context.Result.Page.PagePositions.Add(new Kooboo.CMS.Sites.Models.HtmlBlockPosition()
                {
                    BlockName = obj.BlockName,
                    LayoutPositionId = obj.OwnerPosition.Name,
                    Order = obj.Order.HasValue ? obj.Order.Value : 0
                });
            }
            else
            {
                var markup = string.Format(renderCode, obj.BlockName);
                var markupNode = NodeExtension.CreateNode(markup);
                ReplateInner(obj, markupNode);
            }

            context.Result.HtmlBlocks.Add(htmlBlock);
        }

        #region IParser<IHtmlBlockPart> Members

        public void Parse(IHtmlBlockPart obj)
        {
            var renderCode = "@Html.FrontHtml().RenderHtmlBlock(\"{0}\")";
            FillResult(this.Context, obj, renderCode);
        }

        #endregion
    }
}
